package client
{
	import flare.physics.IForce;
	import flare.physics.Particle;
	import flare.physics.Simulation;
	import flare.physics.Spring;
	import flare.physics.SpringForce;
	
	public class CustomSpringForce extends SpringForce implements IForce
	{		
		/**
		 * Applies this force to a simulation.
		 * @param sim the Simulation to apply the force to
		 */
		public override function apply(sim:Simulation):void
		{
			var s:Spring, p1:Particle, p2:Particle;
			var dx:Number, dy:Number, dn:Number, dd:Number, k:Number, fx:Number, fy:Number, d:Number;

			for (var i:uint=0; i<sim.springs.length; ++i) {
				s = Spring(sim.springs[i]);
				p1 = s.p1;
				p2 = s.p2;
				if (s.edge != null && !s.edge.visible) {
					continue;
				}
				dx = p1.x - p2.x;
				dy = p1.y - p2.y;
				dn = Math.sqrt(dx*dx + dy*dy);
				dd = dn<1 ? 1 : dn;
				
				k  = s.tension * (dn - s.restLength);
				k += s.damping * (dx*(p1.vx-p2.vx) + dy*(p1.vy-p2.vy)) / dd;
				k /= dd;

				// provide a random direction when needed
				if (dn==0) {
					dx = 0.01 * (0.5-Math.random());
					dy = 0.01 * (0.5-Math.random());
				}

				d = 200;
				
				if (Math.abs(dx) <= d) {
					dx = 0;
				} else if (dx < 0) {
					dx += d;
				} else {
					dx -= d;
				}
				if (Math.abs(dy) <= d) {
					dy = 0;
				} else if (dy < 0) {
					dy += d;
				} else {
					dy -= d;
				}
				
				fx = -k * dx;
				fy = -k * dy;
				
				p1.fx += fx; p1.fy += fy;
				p2.fx -= fx; p2.fy -= fy;
			}
		}
		
	} // end of class SpringForce
}